<template>
  <div style="width: 100%;height: calc(100vh - 84px);pointer-events: auto;" id="distributionDetails">
    <div id="container" style="width: 100%;height: calc(100vh - 84px);"></div>
    <div style="position: absolute;top: 20px;width: 100%;">
      <div style="display: flex;justify-content: space-between;padding: 0 50px;">
        <div style="display: flex;flex-direction: column; gap: 20px;">
          <!-- <div style="display: flex; justify-content: center;align-items: center;">
            <img src="../../../assets/img/ren.png" style="width: 25px;">
            <span style="margin: 0 8px;font-weight: bold;font-size: 14px;">流转人数：</span>
            <span>10</span>
          </div>
          <div style="display: flex; justify-content: center;align-items: center;">
            <img src="../../../assets/img/qian.png" style="width: 25px;">
            <span style="margin: 0 8px;font-weight: bold;font-size: 14px;">签字人数：</span>
            <span>8</span>
          </div>
          <div style="display: flex; justify-content: center;align-items: center;">
            <img src="../../../assets/img/xiao.png" style="width: 25px;">
            <span style="margin: 0 8px;font-weight: bold;font-size: 14px;">销毁人数：</span>
            <span>8</span>
          </div> -->
        </div>
        <div>
          <h2>{{ content }}流程图</h2>
        </div>
        <div><el-button type="primary" size="medium" round @click.prevent="handlExport">导出流程图</el-button></div>
      </div>

    </div>
    <el-dialog :visible.sync="showitemDialog" width="60%">
      <el-descriptions class="margin-top" title="节点详情" :column="2" border>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            姓名
          </template>
          {{ target.userName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-mobile-phone"></i>
            部门
          </template>
          {{ target.deptName }}
        </el-descriptions-item>
      </el-descriptions>
      <h3>相关流程</h3>
      <el-table :data="target.detailInfos" style="width: 100%">
        <el-table-column align="center" prop="senderName" label="发送人" width="180">
        </el-table-column>
        <el-table-column align="center" prop="name" label="是否签名" width="180">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.status == 2">
              <span style="font-size: 16px;">&nbsp&nbsp是&nbsp&nbsp</span>
            </el-tag>
            <el-tag type="danger" v-else>
              <span style="font-size: 16px;">&nbsp&nbsp否&nbsp&nbsp</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="address" label="是否销毁">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.isDestroyed == 2">
              <span style="font-size: 16px;">&nbsp&nbsp是&nbsp&nbsp</span>
            </el-tag>
            <el-tag type="danger" v-else>
              <span style="font-size: 16px;">&nbsp&nbsp否&nbsp&nbsp</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="签名">
          <template slot-scope="scope">
            <span v-if="!scope.row.filePath">
              暂无签名
            </span>
            <img v-else @click="handlekan(scope.row.filePath)"
              style="width: 100%;height: 150px;" :src="scope.row.filePath">
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-image-viewer v-if="showViewer" :on-close="() => { showViewer = false }" :url-list="srcList" />
  </div>

</template>
<script>
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import {URL,minioUrl} from '@/api/api'
import { Graph, Cell, Node, Dom } from '@antv/x6'
import { register } from '@antv/x6-vue-shape'
import itemDiv from "./item.vue"
import dagre from 'dagre'
import { Export } from '@antv/x6-plugin-export'
import DistributionApi from '../api/distribution'
import { base64ToFile } from "../../../utils/index"
import { Message } from 'element-ui'
import data from "../../../views/pdf/content";
export default {
  data() {
    return {
      showitemDialog: false,
      graph: null,
      x6Data: {
        nodes: [
          {
            id: 'node1',
            shape: 'rect',
            x: 40,
            y: 40,
            width: 100,
            height: 40,
            label: 'hello',
            attrs: {
              // body 是选择器名称，选中的是 rect 元素
              body: {
                stroke: '#8f8f8f',
                strokeWidth: 1,
                fill: '#fff',
                rx: 6,
                ry: 6,
              },
            },
          },
          {
            id: 'node2',
            shape: 'rect',
            x: 160,
            y: 180,
            width: 100,
            height: 40,
            label: 'world',
            attrs: {
              body: {
                stroke: '#8f8f8f',
                strokeWidth: 1,
                fill: '#fff',
                rx: 6,
                ry: 6,
              },
            },
          },
        ],
        edges: [
          {
            shape: 'edge',
            source: 'node1',
            target: 'node2',
            label: 'x6',
            attrs: {
              // line 是选择器名称，选中的边的 path 元素
              line: {
                stroke: '#8f8f8f',
                strokeWidth: 1,
              },
            },
          },
        ],
      },
      content: "",
      target: [],
      URL,
      showViewer: false,
      srcList: [],
      minioUrl
    }
  },
  components: {
    ElImageViewer
  },
  mounted() {
    // 自定义边

    register({
      shape: 'custom-vue-node',
      width: 300,
      height: 125,
      component: itemDiv
    })
    this.$nextTick(() => {
      this.graph = new Graph({
        container: document.getElementById('container'),
        panning: true,
        mousewheel: true,
        interacting: false,
        background: {
          color: '#F2F7FA',
        },



      })
      const nodes = [
      ]
      const edges = [
      ]
      this.content = this.$route.query.content
      DistributionApi.getDistributionTree({ 'distributionId': this.$route.query.distributionId, 'relationId': this.$route.query.relationId }).then(res => {

        let respData = res.data.data.data
        respData.nodes.forEach(item => {
          nodes.push(this.createNode(item))
        })
        respData.relations.forEach(item => {
          edges.push(this.createEdge(nodes[item.source], nodes[item.target]))
        })
        this.graph.resetCells([...nodes, ...edges])
        this.layout()
        this.graph.zoomTo(0.8)
        this.graph.centerContent()
        this.graph.on('node:click', ({ node, view }) => {
          // let Sstatus= this.$store.getters.userid ==node.data.receiverId

          // if (node.data.roleName == '数据支撑') return Message.error("根节点无法获取信息")
          DistributionApi.getDistributionDetail({ nodeId: node.data.nodeId, senderId: node.data.senderId }).then(res => {
            if (res.data.code == 200) {
              this.target = res.data.data
              this.showitemDialog = true
            }
          })
          // window.addEventListener('resize', () => {

          //   this.graph.resize();
          // });
        });
        this.graph.use(new Export())
      })

    })
  },
  beforeDestroy() { // 在组件生命周期结束的时候销毁。
    window.removeEventListener('resize', this.adjustGraphSize, false)
  },
  methods: {
    handlekan(url) {
      this.srcList = [url]
      this.showViewer = true
    },
    handlExport() {
      this.$nextTick(() => {
        let targetDom = document.getElementById("distributionDetails")
        const width = targetDom.offsetWidth;
        const height = targetDom.offsetHeight;
        this.graph.exportPNG('流程图', { width: width, height: height })
      })
    },
    layout() {
      const dir = 'LR'
      const nodes = this.graph.getNodes()
      const edges = this.graph.getEdges()
      const g = new dagre.graphlib.Graph()
      g.setGraph({ rankdir: dir, nodesep: 300, ranksep: 110, preventOverlap: true, })
      g.setDefaultEdgeLabel(() => ({}))
      const width = 300
      const height = 110
      nodes.forEach((node) => {
        g.setNode(node.id, { width, height })
      })
      edges.forEach((edge) => {
        const source = edge.getSource()
        const target = edge.getTarget()
        g.setEdge(source.cell, target.cell)
      })
      dagre.layout(g)
      g.nodes().forEach((id) => {
        const node = this.graph.getCellById(id)
        if (node) {
          const pos = g.node(id)
          node.position(pos.x, pos.y)
        }
      })
      // edges.forEach((edge) => {
      //   const source = edge.getSourceNode()
      //   const target = edge.getTargetNode()
      //   const sourceBBox = source.getBBox()
      //   const targetBBox = target.getBBox()

      //   if ((dir === 'LR' || dir === 'RL') && sourceBBox.y !== targetBBox.y) {
      //     const gap =
      //       dir === 'LR'
      //         ? targetBBox.x - sourceBBox.x - sourceBBox.width
      //         : -sourceBBox.x + targetBBox.x + targetBBox.width
      //     const fix = dir === 'LR' ? sourceBBox.width : 0
      //     const x = sourceBBox.x + fix + gap / 2
      //     edge.setVertices([
      //       { x, y: sourceBBox.center.y },
      //       { x, y: targetBBox.center.y },
      //     ])


      //   } else if (
      //     (dir === 'TB' || dir === 'BT') &&
      //     sourceBBox.x !== targetBBox.x
      //   ) {
      //     const gap =
      //       dir === 'TB'
      //         ? targetBBox.y - sourceBBox.y - sourceBBox.height
      //         : -sourceBBox.y + targetBBox.y + targetBBox.height
      //     const fix = dir === 'TB' ? sourceBBox.height : 0
      //     const y = sourceBBox.y + fix + gap / 2
      //     edge.setVertices([
      //       { x: sourceBBox.center.x, y },
      //       { x: targetBBox.center.x, y },
      //     ])
      //   } else {
      //     edge.setVertices([])
      //   }
      // })
    },
    createNode(params) {
      return this.graph.createNode({
        id: params.id,
        shape: 'custom-vue-node',
        data: params,


      })
    },
    createEdge(source, target) {
      return this.graph.createEdge({
        source: { cell: source.id },
        target: { cell: target.id },
        attrs: {
          line: {
            strokeWidth: 2,
            stroke: '#1890FF',
            targetMarker: 'classic',
          },

        },
        router: {
          name: 'metro',
          args: {
            startDirections: ['right'],
            endDirections: ['left'],
          },
        },
      })
    },

    adjustGraphSize() {
      let targetDom = document.getElementById("distributionDetails")
      const width = targetDom.offsetWidth;
      const height = targetDom.offsetHeight;
      this.graph.resize(width, height);
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/ .el-descriptions--mini.is-bordered .el-descriptions-item__cell {
  font-size: 16px;
}

.el-image-viewer__wrapper {
  z-index: 10000 !important;
}
</style>